package cn.TcpUtil;

import java.io.InputStream;
import java.io.ObjectInputStream.GetField;
import java.util.Properties;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

import cn.domain.Tunnel;

import com.serotonin.messaging.WaitingRoomException;
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.ip.IpParameters;
import com.serotonin.modbus4j.msg.ModbusRequest;
import com.serotonin.modbus4j.msg.ModbusResponse;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersRequest;
import com.serotonin.util.queue.ByteQueue;

public class TcpUtil implements Runnable {
	private static int count;
	private static TcpUtil  tcputil;
	private ModbusMaster tcpModBusMaster;
	private static IpParameters ipParameters;
	private static ArrayBlockingQueue<ModbusRequest> requestQueue = new ArrayBlockingQueue<ModbusRequest>(10);
	private static ArrayBlockingQueue<ModbusResponse> responseQueue = new ArrayBlockingQueue<ModbusResponse>(
			10);
	private ModbusFactory modbusFactory = new ModbusFactory();
	private boolean tcpMasterAlive = false;
	private static String ip;
	private static int port;
	private  Thread tcpThread=null;
	static {
		Properties prop = new Properties();
		InputStream in = Object.class.getResourceAsStream("/Modbus.properties");
		try {
			prop.load(in);
			ip = prop.getProperty("ip").trim();
			port = Integer.parseInt(prop.getProperty("port").trim());
			ipParameters=new IpParameters();
			ipParameters.setHost(ip);
			ipParameters.setPort(port);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private  TcpUtil() {

	}
    public static TcpUtil startTcpService(){
    	if(tcputil==null){
    	     tcputil=new TcpUtil();
    	     Thread tcpThread=new Thread(tcputil);
    	     tcpThread.start();
    	     System.out.println("new tCP");
    	     return tcputil;
    	}else{
    		 System.out.println("old tCP");
    		return tcputil;
    	}
    }
	@Override
	public void run() {	
		try {
			tcpModBusMaster = modbusFactory.createTcpMaster(ipParameters, tcpMasterAlive);
			tcpModBusMaster.init();
		} catch (ModbusInitException e) {
			e.printStackTrace();
		}
		while (true) {
			// 用来接受发送
			ModbusRequest request = null;
			// 用来接受返回
			ModbusResponse response = null;
			try {
				// 获取到等待的request 如果5000s后没获取到，进程自动休眠10s
				request = requestQueue.poll(5000,TimeUnit.HOURS);
				if (request != null) {
					// 获取到了request 需要发送。
					count++;
					response = tcpModBusMaster.send(request);
					//发送成功
					responseQueue.add(response);
					
					// 线程随机休息一下
					Long sleepTime=(long) (Math.random() * 500);
					Thread.sleep(2000);
				    System.out.println("count:"+count);
				} else {
					System.out.println("====request没有得到资源程序  即将自动休眠10s");
					Thread.sleep(10000);
					System.out.println("====request没有得到资源程序  自动休眠结束！   ");
				   
				}
			} catch (Exception e1) {
	        count=0;
	         e1.printStackTrace();
			}
		}
	}

	public  ModbusResponse sendRequest(ModbusRequest request) {
		try {
			requestQueue.add(request);
			ModbusResponse response= responseQueue.poll(5000,TimeUnit.SECONDS);
		//	System.out.println("**请求完成***。");
			return response;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


}
